package com.tngames.angrytunisian.game.core;

import static playn.core.PlayN.assets;
import static playn.core.PlayN.graphics;
import static playn.core.PlayN.keyboard;
import static playn.core.PlayN.pointer;

import playn.core.AssetWatcher;
import playn.core.Image;
import playn.core.ImageLayer;

public class Splashscreen implements GameScreen {

	private static final int SPLASHSCREEN_DURATION = 3000;
	private AngryTunisianGame game;
	private boolean splashscreenLoaded;
	private boolean gameResourcesLoaded;
	private boolean animationDone;
	private float animationDuration;

	private ImageLayer devTeamLogoLayer;

	public Splashscreen(AngryTunisianGame game) {
		this.game = game;

		AssetWatcher assetWatcher = new AssetWatcher(
				new AssetWatcher.Listener() {
					@Override
					public void done() {
						initAfterResourcesLoaded();

						preloadGameImages();
					}

					@Override
					public void error(Throwable e) {
						// TODO Show an error message
					}
				});

		addAll(assetWatcher, Resources.DEV_TEAM_LOGO);

		assetWatcher.start();

	}

	private void preloadGameImages() {
		AssetWatcher assetWatcher = new AssetWatcher(
				new AssetWatcher.Listener() {
					@Override
					public void done() {
						gameResourcesLoaded = true;
						mayStartGame();
					}

					@Override
					public void error(Throwable e) {
						// TODO Show an error message
					}
				});

		addAll(assetWatcher, Resources.SLING_SHOT);

		assetWatcher.start();
	}

	private void mayStartGame() {
		if (gameResourcesLoaded && animationDone) {
			graphics().rootLayer().clear();
			game.splashscreenDone();
		}
	}

	private void initAfterResourcesLoaded() {
		// Background Image
		Image backgroundImage = assets().getImage(Resources.BACKGROUND);
		graphics().rootLayer()
				.add(graphics().createImageLayer(backgroundImage));

		graphics().setSize(backgroundImage.width(), backgroundImage.height());

		// Dev Team Logo
		Image devTeamImage = assets().getImage(Resources.DEV_TEAM_LOGO);
		devTeamLogoLayer = graphics().createImageLayer(devTeamImage);
		graphics().rootLayer().add(devTeamLogoLayer);

		animationDuration = 0;

		splashscreenLoaded = true;
	}

	private void addAll(AssetWatcher assetWatcher, String... imagePaths) {
		for (String imagePath : imagePaths) {
			add(assetWatcher, imagePath);
		}
	}

	private void add(AssetWatcher assetWatcher, String imagePath) {
		assetWatcher.add(assets().getImage(imagePath));
	}

	@Override
	public void update(float delta) {
		if (!splashscreenLoaded || animationDone) {
			return;
		}
		animationDuration += delta;

		if (animationDuration > SPLASHSCREEN_DURATION) {
			animationDone = true;
			devTeamLogoLayer.setAlpha(0);
			mayStartGame();
		} else {
			devTeamLogoLayer.setAlpha(1 - animationDuration
					/ SPLASHSCREEN_DURATION);
		}
	}

}
